package yiran.dcolormotd.manager;

import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.CachedServerIcon;
import yiran.daobase.lang.LangHelper;
import yiran.daobase.output.MessageUtils;
import yiran.dcolormotd.DColorMotd;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class IconManager {
    private final JavaPlugin plugin;
    private final ConfigManager configManager;
    private final Map<String, CachedServerIcon> iconCache = new HashMap<>();

    public IconManager(JavaPlugin plugin, ConfigManager configManager) {
        this.plugin = plugin;
        this.configManager = configManager;
        loadIcons();
    }

    public void reloadIcons() {
        iconCache.clear();
        loadIcons();
    }

    private void loadIcons() {
        String[] iconTypes = {"normal", "starting", "maintenance", "full"};
        if (!DColorMotd.isVersionAtLeast(1, 7)) {
            MessageUtils.log("warn", LangHelper.getString("icons_not_supported"));
            return;
        }
        for (String type : iconTypes) {
            String iconPath = configManager.getConfig().getString("icons." + type, "");
            if (!iconPath.isEmpty()) {
                try {
                    File iconFile = new File(plugin.getDataFolder(), iconPath);

                    // 如果文件不存在，尝试从JAR复制
                    if (!iconFile.exists()) {
                        // 检查资源是否存在
                        if (plugin.getResource(iconPath) != null) {
                            plugin.saveResource(iconPath, false);
                            MessageUtils.log("info", LangHelper.getString("icon_created", iconPath));
                        } else {
                            MessageUtils.log("warn", LangHelper.getString("icon_not_found", iconPath));
                            continue; // 跳过此图标
                        }
                    }

                    // 加载图标
                    if (iconFile.exists()) {
                        CachedServerIcon icon = plugin.getServer().loadServerIcon(iconFile);
                        iconCache.put(type, icon);
                        MessageUtils.log("info", LangHelper.getString("icon_loaded", type));
                    }
                } catch (Exception e) {
                    MessageUtils.log("error", LangHelper.getString("icon_load_failed", type, e.getMessage()));
                }
            }
        }
    }

    public CachedServerIcon getIcon(String type) {
        return iconCache.get(type);
    }
}

